package cn.harry.common.utils;

import cn.harry.common.api.ResultCode;
import cn.harry.common.constant.CommonConstant;
import cn.harry.common.exception.ApiException;
import cn.harry.modular.sys.domain.SysUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * ClassName: SecurityUtils Description: 安全服务工具类
 *
 * @author honghh Date 2020/04/13 12:49 Copyright (C) www.tech-harry.cn
 */
public class SecurityUtils {

	public static UserDetails getUserDetails() {
		UserDetails userDetails;
		try {
			userDetails = (UserDetails) SecurityContextHolder.getContext()
					.getAuthentication().getPrincipal();
		}
		catch (Exception e) {
			throw new ApiException(ResultCode.UNAUTHORIZED);
		}
		return userDetails;
	}

	/**
	 * 是否为管理员
	 * @param userId 用户ID
	 * @return 结果
	 */
	public static boolean isAdmin(Long userId) {
		return userId != null && CommonConstant.SUPER_ADMIN_ID == userId;
	}

	public static SysUser getSysUser() {
		try {
			SecurityContext ctx = SecurityContextHolder.getContext();
			Authentication auth = ctx.getAuthentication();
			SysUserDetails sysUserDetails = (SysUserDetails) auth.getPrincipal();
			return sysUserDetails.getSysUser();
		}
		catch (Exception e) {
			throw new ApiException(ResultCode.UNAUTHORIZED);
		}
	}

	public static Long getUserId() {
		return getSysUser().getId();
	}

	public static SysUserDetails getSysUserDetails() {
		try {
			SecurityContext ctx = SecurityContextHolder.getContext();
			Authentication auth = ctx.getAuthentication();
			return (SysUserDetails) auth.getPrincipal();
		}
		catch (Exception e) {
			throw new ApiException(ResultCode.UNAUTHORIZED);
		}
	}

}
